## This function is (slightly edited) from the bartMachine package. It reuses numeric variables,
## but turns characters/ factors into dummies for every level.
## Thanks to bartMachine package
dummify_data2 <- function(data, use_missing_data_dummies_as_covars = FALSE, imputations = NULL){
  #first convert characters to factors
  character_vars = names(which(sapply(data, class) == "character"))
  for (character_var in character_vars){
    data[, character_var] = as.factor(data[, character_var])
  }
  
  factors = names(which(sapply(data, class) == "factor"))
  
  factor_lengths = c()
  for (fac in factors){
    #first create the dummies to be appended for this factor
    dummied = do.call(cbind, lapply(levels(data[, fac]), function(lev){as.numeric(data[, fac] == lev)}))
    #ensure they're named appropriately
    colnames(dummied) = paste(fac, levels(data[, fac]), sep = "_")
    #append them to the data
    data = cbind(data, dummied)
    #delete the factor covariate from the design matrix
    data[, fac] = NULL
    #record the length of this factor
    factor_lengths = c(factor_lengths, ncol(dummied))
  }
  
  #make sure to cast it as a data matrix and return it along with the factor_lengths
  return(data.matrix(data))
}